/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package chuiniurobot;


import chuiniurobot.message.LoginMessage;
import java.net.ConnectException;
import java.net.InetSocketAddress;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.mina.core.RuntimeIoException;
import org.apache.mina.core.future.ConnectFuture;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.filter.codec.textline.TextLineCodecFactory;
import org.apache.mina.transport.socket.SocketConnector;
import org.apache.mina.transport.socket.nio.NioSocketConnector;

/**
 *
 * @author zhengji
 */
public class ChuiniuRobot extends IoHandlerAdapter{

    Log logger=LogFactory.getLog(this.getClass());
    private ConnectFuture connectFuture=null;
    public SocketConnector socketConnector;  
    
    String serverHost;
    int port;
    int playerId;//自身ID
    String deviceID;//设备唯一标识
    int vsPlayerID;//对家ID
     int currentGuessAmount=0;// 当前猜测的总数

    boolean hasGuessOne=false;//点数 1 是否被猜测过


    
    int currentGuessNumber=1;//当前猜测的数字
    String[] selfDiceNumbers=new String[5];// 自己摇定的骰子点数
    String[]  vsPlayerDiceNumbers=new String[5];//对家摇定的骰子点数
    
    GameStatusEnum gameStatus= GameStatusEnum.GameStatusNormal;
    
    public GameStatusEnum getGameStatus(){
        return this.gameStatus;
        
    }
    
    public void setGameStatus(GameStatusEnum status){
        this.gameStatus=status;
        initGameSet();
    }
   
    public void startRobot(String host,String port,String playerID,String deviceID){
        
        this.serverHost=host;
        this.port= Integer.parseInt(port);
        this.playerId=Integer.parseInt(playerID);
        this.deviceID=deviceID;
        
       connect(this.serverHost, this.port);
        
    }
     public void connect(String host,int port) {  
        socketConnector = new NioSocketConnector();  
  
        // 长连接  
        // socketConnector.getSessionConfig().setKeepAlive(true);  
  
        
        socketConnector.setConnectTimeoutMillis(35*1000);  
  
 
        socketConnector.getFilterChain().addLast("codec", new ProtocolCodecFilter(new TextLineCodecFactory()));  
          
        
        socketConnector.setHandler(this); 
            InetSocketAddress addr = new InetSocketAddress(host, port);  
        connectFuture = socketConnector.connect(addr);  
    }  
  
    public void sendMessage(final String msg) {  
         
        
        try {  
            connectFuture.awaitUninterruptibly();  
            connectFuture.getSession().write(msg);  
            System.out.println("send message " + msg);  
        } catch (RuntimeIoException e) {  
            if (e.getCause() instanceof ConnectException) {  
                try {  
                    if (connectFuture.isConnected()) {  
                        connectFuture.getSession().close();  
                    }  
                } catch (RuntimeIoException e1) {  
                }  
            }  
        }  
    }  
    
    /**
     * 玩家登录
     */
     private void playerLogin() {
   
           String json=LoginMessage.getLoginJson(this.playerId, this.deviceID);
           
           this.sendMessage(json);
     }
      
    @Override
    public void sessionOpened(IoSession session) throws Exception {
        //玩家登录
        playerLogin();
    }
     @Override
    public void sessionClosed(IoSession session) throws Exception {
       
    }
    
     @Override  
    public void messageSent(IoSession session, Object message) throws Exception {  
        System.out.println(String.format("[%d] messageSent:%s",this.playerId,message));  
        super.messageSent(session, message);  
    }  
    @Override  
    public void messageReceived(IoSession session, Object message) throws Exception {  
       
        if(message==null || message.toString().equals("")) return ;
        
       String msg= new String(message.toString().getBytes(),"UTF-8");
                
        System.out.println(String.format("[playerId:%d]Receive Server message " + msg,this.playerId));  
  
        super.messageReceived(session, msg);  
        
        MSGDispatch dispatch=new MSGDispatch(session,msg);
        dispatch.setRobot(this);
        dispatch.parseMessage();
       
      
     
    }  
    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        
  
                            
       if(args==null || args.length<4){
           System.out.println("用法:java chuiniurobot.ChuiniuRobot serverHost port playerID deviceID");
       }else{
       
       
         new ChuiniuRobot().startRobot(args[0], args[1], args[2], args[3]);
       }
    }

    
    public int getCurrentGuessAmount() {
        return currentGuessAmount;
    }

    public void setCurrentGuessAmount(int currentGuessAmount) {
        this.currentGuessAmount = currentGuessAmount;
    }

    public int getCurrentGuessNumber() {
        return currentGuessNumber;
    }

    public void setCurrentGuessNumber(int currentGuessNumber) {
        if(currentGuessNumber==1){
            this.setHasGuessOne(true);//1 已经被猜测过，不具备万能权限
        }
        this.currentGuessNumber = currentGuessNumber;
    }

    public String[] getSelfDiceNumbers() {
        return selfDiceNumbers;
    }

    public void setSelfDiceNumbers(String[] selfDiceNumbers) {
        this.selfDiceNumbers = selfDiceNumbers;
    }

    public String[] getVsPlayerDiceNumbers() {
        return vsPlayerDiceNumbers;
    }

    public void setVsPlayerDiceNumbers(String[] vsPlayerDiceNumbers) {
        this.vsPlayerDiceNumbers = vsPlayerDiceNumbers;
    }
    public int getPlayerId() {
       return this.playerId;
    }

    public void setPlayerId(int playerId) {
        this.playerId=playerId;
         }

    public int getVSPlayerId() {
        return this.vsPlayerID;
    }

    public void setVSPlayerId(int vsPlayerId) {
        this.vsPlayerID=vsPlayerId;
    }

    public boolean isHasGuessOne() {
        return hasGuessOne;
    }

    public void setHasGuessOne(boolean hasGuessOne) {
        this.hasGuessOne = hasGuessOne;
    }

    /**
     * 初始化游戏设置
     */
    private void initGameSet() {
        this.hasGuessOne=false;
        //this.vsPlayerID=0;
        this.currentGuessAmount=0;
        this.currentGuessNumber=1;
        this.selfDiceNumbers=null;
        this.vsPlayerDiceNumbers=null;
         this.gameStatus=GameStatusEnum.GameStatusNormal;
     }
    
}
